/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.itschapala.ds2.cafeteria.listener;

import javax.faces.application.NavigationHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Santiago
 */
public class ValidarSesion implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
        FacesContext fc = event.getFacesContext();
        UIViewRoot viewRoot = fc.getViewRoot();
        if (viewRoot != null && !viewRoot.getViewId().equalsIgnoreCase("/Login.xhtml")) {
            HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
            if (session == null || session.getAttribute("USUARIO_LOGEADO") == null) {
                NavigationHandler nh = fc.getApplication().getNavigationHandler();
                nh.handleNavigation(fc, null, "Login");
                fc.renderResponse();
            } else {
                String user = (String) session.getAttribute("USUARIO_LOGEADO");
                if (user.equals("Administrador")) {
                } else {
                    if (viewRoot.getViewId().equalsIgnoreCase("/MenuPrincipal.xhtml")||
                            viewRoot.getViewId().equalsIgnoreCase("/PlatillosLista.xhtml")
                            ||viewRoot.getViewId().equalsIgnoreCase("/PlatillosCrearEditar.xhtml")
                            ||viewRoot.getViewId().equalsIgnoreCase("/PlatillosConfirmarEliminar.xhtml")
                            ||viewRoot.getViewId().equalsIgnoreCase("/PlatillosConfirmar.xhtml")
                            ||viewRoot.getViewId().equalsIgnoreCase("/Usuario.xhtml")
                            ||viewRoot.getViewId().equalsIgnoreCase("/UsuarioCrearEditar.xhtml")
                            ||viewRoot.getViewId().equalsIgnoreCase("/UsuarioConfirmar.xhtml")
                            ||viewRoot.getViewId().equalsIgnoreCase("/UsuarioConfirmarEliminar.xhtml")) {
                        NavigationHandler nh = fc.getApplication().getNavigationHandler();
                        nh.handleNavigation(fc, null, "Login");
                        fc.renderResponse();
                    }
                }
            }
        }

    }

    @Override
    public void beforePhase(PhaseEvent event) {
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
